package controllers

import (
	"fmt"
	"github.com/beego/beego/v2/server/web"
	"strings"
	"web-beego.com/v1/models"
)

type BaseController struct {
	web.Controller
	controllerName string
	actionName     string
	currentUser    models.User
}

func (c *BaseController) getUserFromSession() {
	currentUser := c.GetSession("cur-u")
	if currentUser != nil {
		c.currentUser = currentUser.(models.User)
		c.Data["currentUser"] = currentUser
	}
}

func (c *BaseController) SetUserToSession(user models.User) error {
	c.SetSession("cur-u", user)
	return nil
}

func (c *BaseController) streamToJsonResult(code models.ResultCode, msg string, data interface{}) {
	r := &models.JsonResult{ResultCode: code, Msg: msg, Data: data}
	c.Data["json"] = r
	c.ServeJSON()
	c.StopRun()
}

func (c *BaseController) Prepare() {
	c.controllerName, c.actionName = c.GetControllerAndAction()
	c.getUserFromSession()
}

func (c *BaseController) checkLogin() {
	fmt.Println("当前用户：", c.currentUser)
	if c.currentUser.Id == 0 {
		urlStr := c.URLFor("HomeController.Login") + "?url="
		redirectUrl := c.Ctx.Request.URL.Path
		if c.Ctx.Input.IsAjax() {
			referURL := c.Ctx.Input.Refer()
			c.streamToJsonResult(models.CODE302, "请登录", urlStr+referURL)
		}
		c.Redirect(urlStr+redirectUrl, 302)
		c.StopRun()
	}

}

const DefaultLayout = "shared/layout_page.html"

func (c *BaseController) setTpl(template ...string) {
	var tplName string
	layout := DefaultLayout
	switch len(template) {
	case 1:
		tplName = template[0]
	case 2:
		tplName = template[0]
		layout = template[1]
	default:
		//把xxxController中的Controller截断
		ctrlName := strings.ToLower(c.controllerName[0 : len(c.controllerName)-10])
		actionName := strings.ToLower(c.actionName)
		tplName = ctrlName + "/" + actionName + ".html"
	}
	c.Layout = layout
	c.TplName = tplName
}
